<script setup lang="ts">
import { ref } from "vue";
import { Picture, Folder } from "@element-plus/icons-vue";

interface Emits {
  (e: "send", content: string, type: string): void;
  (e: "typing", isTyping: boolean): void;
  (e: "uploadImage", file: File): void;
  (e: "uploadFile", file: File): void;
}

const emit = defineEmits<Emits>();

const inputContent = ref("");
const fileInputRef = ref<HTMLInputElement>();
const imageInputRef = ref<HTMLInputElement>();

let typingTimer: any = null;

const handleInput = () => {
  emit("typing", true);

  if (typingTimer) clearTimeout(typingTimer);
  typingTimer = setTimeout(() => {
    emit("typing", false);
  }, 3000);
};

const handleSend = () => {
  const content = inputContent.value.trim();
  if (!content) return;

  emit("send", content, "text");
  inputContent.value = "";
};

const handleKeyDown = (event: KeyboardEvent) => {
  if (event.key === "Enter" && !event.shiftKey) {
    event.preventDefault();
    handleSend();
  }
};

const selectImage = () => {
  imageInputRef.value?.click();
};

const selectFile = () => {
  fileInputRef.value?.click();
};

const handleImageSelect = (event: Event) => {
  const target = event.target as HTMLInputElement;
  const file = target.files?.[0];
  if (file) {
    emit("uploadImage", file);
    target.value = "";
  }
};

const handleFileSelect = (event: Event) => {
  const target = event.target as HTMLInputElement;
  const file = target.files?.[0];
  if (file) {
    emit("uploadFile", file);
    target.value = "";
  }
};
</script>

<template>
  <div class="message-input">
    <div class="input-toolbar">
      <el-button :icon="Picture" circle @click="selectImage" />
      <el-button :icon="Folder" circle @click="selectFile" />
    </div>

    <div class="input-area">
      <el-input
        v-model="inputContent"
        type="textarea"
        :rows="3"
        placeholder="Type your message..."
        @input="handleInput"
        @keydown="handleKeyDown"
      />
    </div>

    <div class="input-actions">
      <el-button type="primary" :disabled="!inputContent.trim()" @click="handleSend"> Send </el-button>
    </div>

    <input
      ref="imageInputRef"
      type="file"
      accept="image/*"
      style="display: none"
      @change="handleImageSelect"
    />
    <input ref="fileInputRef" type="file" style="display: none" @change="handleFileSelect" />
  </div>
</template>

<style lang="scss" scoped>
.message-input {
  padding: 16px;
  background: #fff;
  border-top: 1px solid #dcdfe6;
}

.input-toolbar {
  display: flex;
  gap: 8px;
  margin-bottom: 12px;
}

.input-area {
  margin-bottom: 12px;

  :deep(.el-textarea__inner) {
    resize: none;
    border-radius: 8px;
  }
}

.input-actions {
  display: flex;
  justify-content: flex-end;
}
</style>
